/* Copyright 2008 Bas van den Berg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "KillStats.h"
#include "Room.h"
#include "StringBuilder.h"
#include "Table.h"

using namespace Chronos;
using namespace std;


KillStat::KillStat(const std::string& mobName_, const std::string& roomName_)
    : mobName(mobName_)
    , roomName(roomName_)
    , count(1)
{}

KillStat::KillStat(const KillStat& rhs)
    : mobName(rhs.mobName)
    , roomName(rhs.roomName)
    , count(rhs.count)
{}

bool KillStat::operator< (const KillStat& rhs) {
    return rhs.count < count;
}



bool KillStats::handleObjectEvent(MudObject& object, MudObjectEvent event) {
    if (event == OBJECT_DESTRUCTION) return false;
    if (event == MUDMOBILE_DEATH) {
        addKill(object.getName(), object.getRoom()->getName());
        return false;
    }
    return true;
}


void KillStats::print(StringBuilder& buffer) const {
    Table table(3);
    for (KillsConstIter iter = kills.begin(); iter != kills.end(); ++iter) {
        table.addCell(iter->mobName);
        table.addCell(iter->roomName);
        table.addCell(iter->count);
    }
    table.write(buffer);
}


void KillStats::addKill(const string& mobName, const string& roomName) {
    for (KillsIter iter = kills.begin(); iter != kills.end(); ++iter) {
        if (iter->mobName == mobName && iter->roomName == roomName) {
            iter->count++;
            kills.sort();
            return;
        }
    }
    kills.push_back(KillStat(mobName, roomName));
}

